﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;

namespace SiGeSIB.Data.Common
{
	public static class SqlExtensions
	{
		public const string CARRIAGE_RETURN = "\n";

		public static string GetStringIds(this int[] ids)
		{
			return ids != null ? ids.Aggregate<int, string>("", (acum, id) => string.Concat(acum, id, CARRIAGE_RETURN)) : null;
		}

		public static void AddParameterWithValues(this SqlCommand cmd, string paramName, object value)
		{
			if (cmd != null && !string.IsNullOrEmpty(paramName) && value != null)
			{
				SqlParameter param = cmd.CreateParameter();
				param.ParameterName = paramName.StartsWith("@") ? paramName : string.Concat("@", paramName);
				param.SqlDbType = GetDBType(value);
				param.SqlValue = value;
				cmd.Parameters.Add(param);
			}
		}

		private static SqlDbType GetDBType(this object obj)
		{
			Type type = obj.GetType();
			SqlParameter param;
			TypeConverter tc;
			param = new SqlParameter();
			tc = TypeDescriptor.GetConverter(param.DbType);
			if (tc.CanConvertFrom(type))
			{
				param.DbType = (DbType)tc.ConvertFrom(type.Name);
			}
			else
			{
				// try to forcefully convert
				try
				{
					param.DbType = (DbType)tc.ConvertFrom(type.Name);
				}
				catch (Exception)
				{
					// ignore the exception
				}
			}
			return param.SqlDbType;
		}

		public static int ExecuteWithReturnValue(this SqlCommand cmd)
		{
			SqlParameter param = cmd.CreateParameter();
			param.SqlDbType = SqlDbType.Int;
			param.Direction = ParameterDirection.Output;
			param.ParameterName = "@RETURN_VALUE";
			cmd.Parameters.Add(param);

			cmd.ExecuteNonQuery();

			return (int)param.Value;
		}

		public static T GetEnum<T>(this SqlDataReader dr, int index) where T : struct
		{
			return (T)Enum.ToObject(typeof(T),dr.GetInt32(index));
		}
	}
}
